package communication.majiang
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import communication.CertManager;
	import communication.ProtoFactory;
	import communication.ServerAddress;
	import communication.SocketConnected;
	
	import modules.GameDispatcher;
	
	import protobuf.MSPKG_HELLO_WORLD_REQ;


	public class MajiangSocket extends SocketConnected
	{
		private var timer:Timer = new Timer(240000);
		
		/**
		 * 是否已经授权
		 **/
		private var _isAuth:Boolean = false;

		public function get isAuth():Boolean
		{
			return _isAuth;
		}

		/**
		 * 通过授权
		 */
		public function set isAuth(value:Boolean):void
		{
			_isAuth = value;
		}

		private var msgProcesser:MajiangMsgProcessor = MajiangMsgProcessor.getInstance();

		public function MajiangSocket(serverArray:Array)
		{
			super(serverArray);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
			timer.start();
		}

		private function get majiangMsgSender():MajiangMsgSender
		{
			return MajiangMsgSender.instance;
		}

		private function get dispatcher():GameDispatcher
		{
			return GameDispatcher.instance;
		}

		/**
		 * 麻将服务器连接成功
		 */
		override protected function connectionComplete():void
		{
			logger("麻将Socket连接成功");
			var address:ServerAddress = _serverArray[currentServerIndex];

			majiangMsgSender.sendSessionCert(address);
		}

		/**
		 * 麻将服务器重连成功
		 */
		override protected function reconnectSuccess():void
		{
			logger("麻将Socket重连成功");
			var address:ServerAddress = _serverArray[currentServerIndex];

			majiangMsgSender.sendSessionCert(address);
		}

		/**
		 * 麻将服连接关闭
		 */
		override protected function closeHandler(event:Event):void
		{
			/*super.closeHandler(event);
			logger("麻将服连接关闭");

			if(TablesDataManager.getEnterTableNum() > 0)
			{
				dispatcher.dispatchEvent(new GameEvent(GameEvent.SHOW_INFO, {info: "失去游戏服务器连接，所有进入的桌子已退出"}));
			}

			dispatcher.dispatchEvent(new GameEvent(GameEvent.majiang_server_close, {socket: this}));*/
		}

		/**
		 * 麻将服务器连接失败
		 */
		override protected function connectFailed():void
		{
			logger("majiang Socket connection failed..");
		}

		override protected function dispatchMessage(messageId:uint, data:ByteArray):void
		{
			var prePosition:int = data.position;

			ProtoFactory.getMSProto().Decode(messageId, data, msgProcesser);

		}
		
		/**
		 * 对服务器发送协议 向flash或服务器表示socket还需要活着
		 */		
		private function onTimer(event:Event):void
		{
			if(hasConnected() && isAuth)
			{
				var hello:MSPKG_HELLO_WORLD_REQ = new MSPKG_HELLO_WORLD_REQ();
				hello.int1 = 1;
				hello.str1 = CertManager.getInstance().convertStringToByteArray("a");
				hello.str2 = CertManager.getInstance().convertStringToByteArray("b");
				send(MSProto.MSID_HELLO_WORLD_REQ,hello);
				logger("发送心跳包，向flash或服务器表示socket还需要活着");
			}
		}
	}
}
